package com.longmao.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.longmao.commonutils.R;
import com.longmao.servicebase.handler.LongMaoException;
import com.longmao.vod.service.VodService;
import com.longmao.vod.utils.AliyunVodSDKUtils;
import com.longmao.vod.utils.VodPropertiesConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author longmao
 * @date 2022/2/10 11:23
 * Content:
 */
@RestController
//@CrossOrigin
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    /**
     * 上传视频到 aliyun
     * @param file
     * @return
     */
    @PostMapping("/uploadVideoAliyun")
    public R uploadVideoAliyun(MultipartFile file) {
        //获取上传文件
        String videoId = vodService.uploadVideoAliyun(file);
        return R.ok().data("videoId", videoId);
    }

    /**
     * 根据id删除阿里云中的视频
     * @param videoId
     * @return
     */
    @DeleteMapping("/deleteVodVideo/{videoId}")
    public R deleteVodVideo(@PathVariable String videoId) {
        vodService.deleteVodVideoById(videoId);
        return R.ok();
    }

    @DeleteMapping("/delete-batch")
    public R deleteBatch(@RequestParam("videoIds") List<String> videoIds){
        vodService.deleteVodVideoIds(videoIds);
        return R.ok();
    }

    /**
     * 根据视频id获取视频凭证
     * @param videoId
     * @return
     */
    @GetMapping("/getVideoPlayAuth/{videoId}")
    public R getVideoPlayAuth(@PathVariable String videoId) {
        try {
            //创建初始化对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(VodPropertiesConstant.ACCESS_KEY_ID, VodPropertiesConstant.ACCESS_KEY_SECRET);
            //创建获取视频凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request中设置视频id
            request.setVideoId(videoId);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            return R.ok().data("playAuth", response.getPlayAuth());
        }catch (Exception e) {
            throw new LongMaoException(20001, "播放视频失败");
        }
    }
}
